
import { DependencyContainer } from 'tsyringe';
import { ROOT } from '@sker/core';
import { join } from 'path';
import axios from 'axios';
import { useAddonSetting } from '@sker/runtime'
export interface HasuraRunner<T> {
    (): Promise<{ variables: T, query: string }>;
}
export const useHasura = async <O, T>(injector: DependencyContainer, runner: HasuraRunner<T>) => {
    const root = injector.resolve(ROOT)
    const env = injector.resolve<any>('ENV')
    let config = {
        URL: env.HASURA_URL,
        ADMIN_SECRET: env.HASURA_ADMIN_SECRET,
    }

    let hasuraConfig = await useAddonSetting('@imeepos/hasura')
    if (hasuraConfig) {
        config = {
            ...config,
            ...hasuraConfig
        }
    }
    // 兼容之前版本
    if (!config) {
        const jsonFile = join(`${root}`, 'data/plugins', `@sker/hasura.json`)
        config = require(jsonFile)
    }
    const { variables, query } = await runner();
    return axios.post(config.URL + '/v1/graphql', { variables, query }, {
        headers: {
            [`x-hasura-admin-secret`]: config.ADMIN_SECRET,
            [`content-type`]: `application/json`
        }
    }).then(res => res.data)
}
export const test = async (injector: DependencyContainer) => {
    const now = Date.now()
    await useHasura<any, any>(injector, async () => ({ variables: {}, query: `` }));
    return { success: true, message: 'ok', data: `${(Date.now() - now) / 1000}s` };
}
export default useHasura;
